import NetConfig from "./SocketConfig";
import Dictionary from "./Dictionary";
import SocketConfig from "./SocketConfig";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SocketRequest extends cc.Component {
    /**
     * 当前的WebSocket对象
     */
    private static _socket: WebSocket;

    /**
     * 回调事件的字典
     */
    private static _socket_events: Dictionary<number, Function>;

    /**
     * 是否处于连接状态
     */
    private static is_connected: boolean = false;

    /**
     * websocket连接
     * @param _open 连接成功回调
     * @param _error 连接错误回调
     * @param _close 关闭连接回调
     * @param _response 接收到消息回调
     */
    public static connect(_open: Function, _error: Function, _close: Function, _response: Function) {
        if (SocketRequest._socket == null) {
            SocketRequest._socket = new WebSocket(NetConfig.websocket_ip, [], SocketConfig.cert.nativeUrl);
            if (SocketRequest._socket_events == null) SocketRequest._socket_events = new Dictionary<number, Function>();

            SocketRequest._socket.onopen = () => {
                SocketRequest.is_connected = true;
                if (_open != null) _open();
            }

            SocketRequest._socket.onerror = (err) => {
                if (_error != null) _error(err);
                SocketRequest.is_connected = false;
                SocketRequest._socket = null;
            }

            SocketRequest._socket.onclose = (data) => {
                if (SocketRequest.is_connected) {
                    if (_close != null) _close(data);
                    SocketRequest.is_connected = false;
                    SocketRequest._socket = null;
                }
            }

            SocketRequest._socket.onmessage = (response) => {
                let data = JSON.parse(response.data);
                if (SocketRequest._socket_events.containkey(data.protocol)) {
                    SocketRequest._socket_events.get(data.protocol)(data);
                }
                else if (_response != null) {
                    _response(data)
                }
            }
        }
    }

    /**
     * 注册事件
     * @param protocol 事件的识别id
     * @param callback 事件回调
     */
    public static register(protocol: number, callback: Function) {
        SocketRequest._socket_events.put(protocol, callback);
    }

    /**
     * 向服务器发送消息
     * @param msg 消息内容
     * @return 发送消息成功返回true
     */
    public static send(msg: string) {
        if (SocketRequest._socket.readyState == 1) {
            SocketRequest._socket.send(msg);
            return true;
        } else {
            console.log("链接断开");
            SocketRequest._socket.close()
            return false;
        }
    }

    public static isConnect(): boolean {
        return SocketRequest.is_connected;
    }
}
